/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var markersArray = [];
var choiceID="";
var geocoder = null;
function getXMLObject()  //XML OBJECT
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlhttp;  // Mandatory Statement returning the ajax object created
}
            
/////////////////////////////////////////////////////////////////////////////////////////////
var map;
var image = new google.maps.MarkerImage('images/Phone-icon.png',
    // This marker is 20 pixels wide by 32 pixels tall.
    new google.maps.Size(40, 40),
    // The origin for this image is 0,0.
    new google.maps.Point(0,0),
    // The anchor for this image is the base of the flagpole at 0,32.
    new google.maps.Point(0, 32));

function initialize(latitude,longitude) {
    var latlng = new google.maps.LatLng(latitude,longitude);
    var myOptions = {
        zoom: 13,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
}
  
var count = 0;
var timer;
function loadSites(phoneID) {
    var xmlrequest = new getXMLObject();
    xmlrequest.onreadystatechange =  function()
    {
        if (xmlrequest.readyState == 4) {
            if(xmlrequest.status == 200) {
                var doc = xmlrequest.responseXML;
                siteMarkers = doc.documentElement.getElementsByTagName("com.tthdhm.truyvetduongdi.pojo.PositionPOJO");
                displaySitesMarkers();
            }
            else {
                alert("Error during AJAX call. Please try again");
            }
        }
    }        
    xmlrequest.open("post", "PositionServlet?action=addMarker&id="+phoneID, true);            
    xmlrequest.send();
    timer= setTimeout("loadSites("+phoneID+")", 1000);
}

function displaySitesMarkers() {
    deleteOverlays();
    for (var i = 0; i < siteMarkers.length; i++) {
        // obtain the attributes of each marker
                    
        var lat = parseFloat(siteMarkers[i].getElementsByTagName("latitude")[0].firstChild.nodeValue);                    
        var lng = parseFloat(siteMarkers[i].getElementsByTagName("longitude")[0].firstChild.nodeValue);
        var id = siteMarkers[i].getElementsByTagName("datetime")[0].firstChild.nodeValue;
        var label = siteMarkers[i].getElementsByTagName("address")[0].firstChild.nodeValue;
        var location = new google.maps.LatLng(lat,lng);
        var marker = new google.maps.Marker({
            position: location, 
            map: map,
            icon:image,
            title:label,
            id:id
        });
        google.maps.event.addListener(marker, 'click', function() {
            var myHtml = "<b>#" + id + "</b><br/>" + label;
            map.openInfoWindowHtml(location, myHtml);
        }); 
        markersArray.push(marker);       
    }
}

function loadTimer(phoneID){
    if(choiceID==""){
        $("#txtTelephoneID"+phoneID).addClass("Choice");
        choiceID="#txtTelephoneID"+phoneID;
    }else{
        $("#txtTelephoneID"+phoneID).addClass("Choice");
        $(choiceID).removeClass("Choice");
        choiceID="#txtTelephoneID"+phoneID;
    }
    deleteOverlays();
    clearTimeout(timer);
    loadSites(phoneID);
    loadVictimInfo(phoneID);
    return false;
}

function deleteOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

function loadVictimInfo(id){
    $.ajax({
        url: "VictimServlet",
        type: "POST",
        data:{
            'action':'VictimInfo',
            'ID': id
        },
        beforeSend: function(){
            var srcImg = "<img src='images/Loading.gif' width='50px' height='50px'/>";
            $("#Info").html(srcImg);
        },
        success : function(data) {
            $("#Info").html(data);
        },
        error : function() {
            $("#Info").html("Get database incorrect!");
        }
    });
}

function loadPersonInfo(id){
    if(choiceID==""){
        $("#"+id).addClass("Choice");
        choiceID="#"+id;
    }else{
        $("#"+id).addClass("Choice");
        $(choiceID).removeClass("Choice");
        choiceID="#"+id;
    }
    deleteOverlays();
    clearTimeout(timer);
    $.ajax({
        url: "CustomerServlet",
        type: "POST",
        data:{
            'action':'CustomerInfo'
        },
        beforeSend: function(){
            var srcImg = "<img src='images/Loading.gif' width='50px' height='50px'/>";
            $("#Info").html(srcImg);
        },
        success : function(data) {
            $("#Info").html(data);
        },
        error : function() {
            $("#Info").html("Get database incorrect!");
        }
    });
    return false;
}

function changeEnable(){
    if($('#txtChange').is(':checked')){
        $('#txtFullname').removeAttr('disabled');
        $('#txtBirthday').removeAttr('disabled');
        $('#txtEmail').removeAttr('disabled');
        $('#txtAddress').removeAttr('disabled');
        $('#txtSex').removeAttr('disabled');
        $('#txtRelation').removeAttr('disabled');
        $('#txtTel').removeAttr('disabled');
    }else{
        $('#txtFullname').attr("disabled", "disabled"); 
        $('#txtBirthday').attr("disabled", "disabled"); 
        $('#txtEmail').attr("disabled", "disabled");
        $('#txtAddress').attr("disabled", "disabled");
        $('#txtSex').attr("disabled", "disabled"); 
        $('#txtRelation').attr("disabled", "disabled"); 
        $('#txtTel').attr("disabled", "disabled"); 
    }
}

function checkValueLogin(){
    if(($("#txtUsername").val())=="")
    {
        $("#error").html("Bạn chưa nhập tên đăng nhập")
        return false;
    }
    
    if(($("#txtPassword").val())=="")
    {
        $("#error").html("Bạn chưa nhập mật khẩu")
        return false;
    }
    return true;
}

function changePassword()
{
    if(choiceID==""){
        $("#changePassword").addClass("Choice");
        choiceID="#changePassword";
    }else{
        $("#changePassword").addClass("Choice");
        $(choiceID).removeClass("Choice");
        choiceID="#changePassword";
    }
    var data="<table style='width:400px; height:300px;'><tr>"
    +"<td class='Label'>Mật khẩu cũ</td>"
    +"<td>"
    +"<input type='password' name='txtOldPassword' id='txtOldPassword' class='Textbox'/>"
    +"</td>"
    +"</tr>"
    +"<tr>"
    +"<td class='Label'>Mật khẩu mới</td>"
    +"<td>"
    +"<input type='password' name='txtNewPassword' id='txtNewPassword' class='Textbox'/>"
    +"</td>"
    +"</tr>"
    +"<tr>"
    +"<td class='Label'>Xác nhận mật khẩu mới</td>"
    +"<td>"
    +"<input type='password' name='txtPasswordConfirm' id='txtPasswordConfirm' class='Textbox'/>"
    +"</td>"
    +"</tr>"
    +"<tr>"
    +"<td class='Label'></td>"
    +"<td align='center'>"
    +"<input type='button' name='btSave' id='btSave' class='button' value='Lưu'/>"
    +"</td>"
    +"</tr>"
    +"</table>";
    $("#Info").html(data);
    return false;
}

function getAddress(lat,lang){
    geocoder = new GClientGeocoder();
    var latlng2 = new google.maps.LatLng(lat, lang);
    if (latlng2) {
        geocoder.getLocations(latlng2, function(addresses) {
            if(addresses.Status.code != 200) {
                alert("reverse geocoder failed to find an address for " + latlng2.toUrlValue());
            }
            else {
                address = addresses.Placemark[0];
                var myHtml = address.address;
                alert(myHtml);
                map.openInfoWindow(latlng2, myHtml);
            }
        });
    }
}